<template>
  <div class="class-student-tree">
    <ContentWrap class="!mb-0">
      <div class="mb-10px">
        <el-input v-model="filterText" placeholder="搜索班级" clearable>
          <template #prefix>
            <Icon icon="ep:search" />
          </template>
        </el-input>
      </div>
      <div class="tree-container">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          :filter-node-method="filterNode"
          :load="loadNode"
          lazy
          node-key="id"
          highlight-current
          check-on-click-node
          accordion
          :default-expanded-keys="defaultExpandedKeys"
          @current-change="handleNodeClick"
        />
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElTree } from 'element-plus'
import { defaultProps } from '@/utils/tree'
import { ClassesApi } from '@/api/school/classes'
import { StudentApi } from '@/api/school/student'

// 定义组件名称
defineOptions({ name: 'ClassStudentTree' })

// 定义事件
const emit = defineEmits<{
  nodeClick: [data: any, node: any]
}>()

// 筛选相关
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref([])
const defaultExpandedKeys = ref([]) // 默认展开的节点key

// 树节点过滤
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

// 获取班级树数据
const getClassesTree = async () => {
  try {
    const res = await ClassesApi.getClassesList()
    res.forEach((item: any) => {
      if (item?.name?.includes('景秀')) {
        item.id = 'jingxiu'
      } else {
        item.id = 'yuanhu'
      }
    })
    treeData.value = res

    // 提取节点的ID作为默认展开的节点
    const expandedKeys: any = []
    const extractClassIds = (nodes) => {
      if (!nodes || nodes.length === 0) return

      nodes.forEach((node: any) => {
        // 节点添加到默认展开列表
        if (node.children && node.children.length > 0) {
          expandedKeys.push(node.id)
        }

        // 递归处理子节点
        if (node.children) {
          extractClassIds(node.children)
        }
      })
    }

    extractClassIds(res)
    defaultExpandedKeys.value = expandedKeys
    treeRef.value?.setCurrentKey('yuanhu')
  } catch (e) {
    console.error('获取班级数据失败:', e)
  }
}

// 懒加载节点
const loadNode = async (node: any, resolve: any) => {
  // 点击班级节点时加载学生列表
  if (node.level === 2) {
    try {
      const res = await StudentApi.getSimpleStudentList(node.data.id)
      const students = res.map((item: any) => {
        // 为学生节点添加唯一标识，避免与班级ID冲突
        return {
          id: `student_${item.id}`, // 添加前缀确保唯一性
          name: item.studentName,
          leaf: true,
          studentId: item.id, // 保存原始学生ID
          type: 'student'
        }
      })
      resolve(students)
    } catch (e) {
      resolve([])
    }
  }
  // 其他层级返回节点的子数据
  else {
    resolve(node?.data?.children || [])
  }
}

// 处理节点点击
const handleNodeClick = (data: any, node: any) => {
  // 清空之前的查询条件
  const queryParams: any = {}
  if (node.level === 1) {
    queryParams.schoolCode = data.id
  }
  // 如果是班级节点
  if (node.level === 2) {
    queryParams.schoolCode = node.parent.data.id
    queryParams.classId = data.id
  }
  // 如果是学生节点
  else if (node.level === 3) {
    // 使用原始学生ID而不是带前缀的ID
    const parentNode = node.parent
    queryParams.schoolCode = parentNode.parent.data.id
    queryParams.studentId = data.studentId || data.id
    queryParams.classId = parentNode.data.id
  }
  emit('nodeClick', queryParams, node)
}

// 监听筛选框变化
watch(filterText, (val) => {
  treeRef.value?.filter(val)
})

// 初始化
onMounted(() => {
  getClassesTree()
})

// 暴露方法给父组件
defineExpose({
  getClassesTree
})
</script>

<style lang="scss" scoped>
.tree-container {
  height: calc($content-height - 64px);
  overflow-y: auto;
}
</style>
